<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class AssistCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:assist {action} {params}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $arguments = $this->arguments();
        if (isset($arguments['action'])) {
            switch ($arguments['action']) {
                //php artisan command:assist table_info "{\"table\":\"users\"}"
                case 'table_info':
                    $data = $arguments['params'];
                    $data = json_decode($data, true);
                    $this->getTableInfo($data['table']);
                    break;
                //php artisan command:assist create_table "{\"table\":\"user_securities\"}"
                case 'create_table':
                    $data = $arguments['params'];
                    $data = json_decode($data, true);
                    $this->getCreateTable($data['table']);
                    break;
                //php artisan command:assist table_all "{\"table\":\"user_securities\"}"
                case 'table_all':
                    $data = $arguments['params'];
                    $data = json_decode($data, true);
                    $this->getTableInfo($data['table']);
                    $this->getCreateTable($data['table']);
                    break;
            }
        }
    }

    public function getTableInfo($table)
    {
        $columns = Schema::getConnection()->getDoctrineSchemaManager()->listTableColumns($table);
        $sql = "\n/**" . "\n";
        $sql .= " * This is the model class for table \"" . $table . "\"" . "\n";
        $sql .= " *\n";
        foreach ($columns as $column) {
//            $sql .= " * @property ". str_replace("\\","",$column->getType()) . " $".$column->getName() . " "  .$column->getComment(). "\n";
            $sql .= " * @property string" . " $" . $column->getName() . " " . $column->getComment() . "\n";

        }

        $sql .= " */\n";
        Log::debug($sql);

    }

    public function getCreateTable($table)
    {
        $columns = Schema::getConnection()->getDoctrineSchemaManager()->listTableColumns($table);
        $sql = "\n";
        foreach ($columns as $column) {
            $sql .= "$" . "this->" . $column->getName() . "= $" . "data['" . $column->getName() . "'];" . "\n";
        }
        Log::debug($sql);
    }

}
